package admin

import (
	"github.com/gin-gonic/gin"
	"go-ecommerce/internal/model"
	"go-ecommerce/internal/service"
	"go-ecommerce/internal/utils"
	"go-ecommerce/internal/validate"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

// CreateAdminHandler 添加管理员
func CreateAdminHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req validate.CreateAdminRequest
		// 参数绑定和验证
		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, http.StatusBadRequest, "参数错误")
			return
		}

		// 调用服务层创建管理员
		if err := service.CreateAdmin(db, req.Username, req.Password); err != nil {
			utils.Error(c, http.StatusInternalServerError, err.Error())
			return
		}

		utils.Success(c, "管理员添加成功")
	}
}

// ListAdminHandler 管理员列表
func ListAdminHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		admins, err := service.GetAdminList(db)
		if err != nil {
			utils.Error(c, 500, "查询失败")
			return
		}
		utils.Success(c, "ok", admins)
	}
}

// UpdateAdminHandler 编辑管理员
func UpdateAdminHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		idStr := c.Param("id")
		id, err := strconv.Atoi(idStr)
		if err != nil {
			utils.Error(c, 400, "ID格式错误")
			return
		}

		var req validate.UpdateAdminRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, 400, "参数错误")
			return
		}

		if err := service.UpdateAdmin(db, uint(id), req.Username); err != nil {
			utils.Error(c, 500, err.Error())
			return
		}

		utils.Success(c, "更新成功")
	}
}

// DeleteAdminHandler 删除管理员
func DeleteAdminHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		idStr := c.Param("id")
		id, err := strconv.Atoi(idStr)
		if err != nil {
			utils.Error(c, 400, "ID格式错误")
			return
		}

		if err := service.DeleteAdmin(db, uint(id)); err != nil {
			utils.Error(c, 500, err.Error())
			return
		}

		utils.Success(c, "删除成功")
	}
}
func AdminInfoHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		uidRaw, exists := c.Get("admin_id")
		if !exists {
			utils.Error(c, 401, "未登录")
			return
		}
		adminID := uidRaw.(uint)
		admin, err := service.GetAdminByID(db, adminID)
		if err != nil {
			utils.Error(c, 500, "获取管理员信息失败")
		}
		utils.Success(c, "ok", gin.H{
			"id":       admin.ID,
			"username": admin.Username,
		})

	}
}

// BindRolesHandler 给管理员绑定角色
func BindRolesHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req validate.BindRolesRequest

		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, http.StatusBadRequest, err.Error())
			return
		}

		// 开始事务
		tx := db.Begin()
		defer func() {
			if r := recover(); r != nil {
				tx.Rollback()
				utils.Error(c, http.StatusBadRequest, "系统异常")
			}
		}()

		// 删除原有角色
		if err := tx.Where("admin_id = ?", req.AdminID).Delete(&model.AdminRole{}).Error; err != nil {
			tx.Rollback()
			utils.Error(c, http.StatusBadRequest, "删除旧角色失败")
			return
		}

		// 添加新角色
		var roles []model.AdminRole
		for _, rid := range req.RoleIDs {
			roles = append(roles, model.AdminRole{
				AdminID: req.AdminID,
				RoleID:  rid,
			})
		}

		if err := tx.Create(&roles).Error; err != nil {
			tx.Rollback()
			utils.Error(c, http.StatusBadRequest, "绑定新角色失败")
			return
		}

		tx.Commit()
		utils.Success(c, "绑定角色成功")

	}
}
